
const db = require('db');
const { toUpdate } = require('tools/sqlString');
const evaluate = require('tools/evaluate');

module.exports = async ctx => {
    const { connection, run, comply } = db.init();
    await run('BEGIN'); // 开始事务
    try {
        await updateSettlement(ctx, run);
        await updateOrder(await queryEntry(ctx, run), comply);
        await run('COMMIT');
        ctx.status = 200;
        ctx.body = 'ok';
    } catch (error) {
        await run('ROLLBACK');
        ctx.status = 500;
        ctx.body = error
    }
    connection.end();
}

/** 更新结算单 */
async function updateSettlement(ctx, run) {
    const id = ctx.params.id;
    const body = ctx.request.body;

    const sql = `
        UPDATE settlement SET ${toUpdate({ ...body, settlementState: '已回款' })}
        WHERE id = ${id}
    `;

    const result = await run(sql);
    if (result.err) {
        throw result.err
    }
}

/** 更新订单 */
async function updateOrder(order, comply) {
    for (let i = 0; i < order.length; i++) {
        const ot = order[i];
        const list = await comply(`
            SELECT settlementEntry.unsettlementAmount
            FROM settlementEntry, settlement
            WHERE 
                settlementEntry.ordersId = ${ot.id} 
                and settlementEntry.settlementId = settlement.id
                and settlement.settlementState = '已回款'
        `)

        let sum = 0;
        list.forEach(e => {
            sum += e.unsettlementAmount
        });

        if (sum === evaluate(`${ot.businessDay}*${ot.price}`)) {
            await comply(`
                UPDATE orders 
                SET ${toUpdate({ orderStatus: '完结' })}
                WHERE id=${ot.id}
            `)
        }
    }
}

/** 查询订单 */
async function queryEntry(ctx, run) {
    const id = ctx.params.id;
    const sqlStr = `
    SELECT o.* 
    FROM settlementEntry as s
    LEFT JOIN orders AS o ON s.ordersId = o.id
    WHERE s.settlementId = ${id}
    `

    const result = await run(sqlStr);
    if (result.err) {
        throw result.err
    }

    return result.rows;
}

